package com.uusee.crawler.xmlwriter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlStatusCodes;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.crawler.util.PathUtils;
import com.uusee.crawler.util.XmlUtils;
import com.uusee.shipshape.bk.model.Baike;
import com.uusee.shipshape.sp.model.Ugc;
import com.uusee.util.StringUtils;

public class UgcXmlWriter extends Processor {
	private static Log log = LogFactory.getLog("UgcXmlWriter"); 
	private String writerRootPath = "/data0/output";
	private XStream xstream;
	
	public UgcXmlWriter(){
		this.xstream = new XStream(new XppDriver() {
			public HierarchicalStreamWriter createWriter(Writer out) {
				return new PrettyPrintWriter(out) {
					protected void writeText(QuickWriter writer, String text) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					}
				};
			}
		});
		this.xstream.setMode(XStream.NO_REFERENCES);
		this.xstream.omitField(Ugc.class, "id");
		this.xstream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", new String[] { "yyyy-MM-dd HH:mm:ss" }));
		this.xstream.alias("ugc", Ugc.class);
	}
	
	
	protected void innerProcess(CrawlURI crawlUri) {
		if (!canProcess(crawlUri)) {
			return;
		}
		
		PrintWriter out = null;
		Ugc ugc = (Ugc)crawlUri.getModel();
		try {
			File xmlFile = createFile(ugc);
			out = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(xmlFile)),"utf-8"));
			out.print(XmlUtils.createHeader());
			xstream.toXML(ugc,out);
		} catch (Exception e) {
			log.error(ugc.getVid()+"-输出XML时发生错误。",e);
		} finally {
			if (out!=null) {
				out.close();
			}
		}
	}
	
	private boolean canProcess(CrawlURI crawlUri) {
		int crawlStatus = crawlUri.getCrawlStatus();
		if (crawlStatus == CrawlStatusCodes.PAGE_PROCESS_SUCCESS) {
			return true;
		} else {
			return false;
		}
	}
	
	public File createFile(Ugc ugc) {
		String videoSite = ugc.getVideoSite();
		String oriId = ugc.getVid();
		String playlistVid = ugc.getPlaylistVid();
		if (StringUtils.isNotEmpty(playlistVid)) {
			oriId = playlistVid;
		}
		StringBuffer xmlFilePathSb = new StringBuffer();
		xmlFilePathSb.append(writerRootPath);
		xmlFilePathSb.append("/");
		xmlFilePathSb.append(videoSite);
		xmlFilePathSb.append("/");
		xmlFilePathSb.append("video");
		xmlFilePathSb.append("/");
		xmlFilePathSb.append(PathUtils.getContainIdSubPathById(oriId));
		File imagePath = new File(xmlFilePathSb.toString());
		if (!imagePath.exists()) {
			imagePath.mkdirs();
		}
		File imageFile = new File(imagePath, oriId + ".xml");
		return imageFile;
	}
	
	public String getXmlPath(Ugc ugc) {
		String videoSite = ugc.getVideoSite();
		String vid = ugc.getVid();
		String playlistVid = ugc.getPlaylistVid();
		if (StringUtils.isNotEmpty(playlistVid)) {
			vid = playlistVid;
		}
		StringBuffer xmlFilePathSb = new StringBuffer();
		xmlFilePathSb.append(writerRootPath);
		xmlFilePathSb.append("/");
		xmlFilePathSb.append(videoSite);
		xmlFilePathSb.append("/");
		xmlFilePathSb.append("video");
		xmlFilePathSb.append("/");
		xmlFilePathSb.append(PathUtils.getContainIdSubPathById(vid));
		return xmlFilePathSb.toString();
	}
	
	public boolean isExistData(Ugc ugc) {
		String videoSite = ugc.getVideoSite();
		String vid = ugc.getVid();
		String playlistVid = ugc.getPlaylistVid();
		if (StringUtils.isNotEmpty(playlistVid)) {
			vid = playlistVid;
		}
		StringBuffer xmlFilePathSb = new StringBuffer();
		xmlFilePathSb.append(writerRootPath);
		xmlFilePathSb.append("/");
		xmlFilePathSb.append(videoSite);
		xmlFilePathSb.append("/");
		xmlFilePathSb.append("video");
		xmlFilePathSb.append("/");
		xmlFilePathSb.append(PathUtils.getContainIdSubPathById(vid));
		File imageFile = new File(xmlFilePathSb.toString() + vid + ".xml");
		if (imageFile.exists()) {
			return true;
		} else {
			return false;
		}
	}


	public void setWriterRootPath(String writerRootPath) {
		this.writerRootPath = writerRootPath;
	}
	
}
